import axios, { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse } from "axios"
import {ResposeErrorHandle} from "./errHandle"
import { useAxios, UseAxiosReturn, UseAxiosOptions } from '@vueuse/integrations/useAxios'
import {watch} from "vue"
import apiKeys from "../api"
import {getToken} from "@/utils/userData"
interface Result<T = any> {
  code: number,
  msg: string,
  data: T
}

const AppUseAxios = (url: string, axiosOptions: AxiosRequestConfig, useAxiosOptions: UseAxiosOptions) => {
  const pathG: string = apiKeys[url]
  const instance: AxiosInstance = axios.create(axiosOptions)

  instance.interceptors.response.use(
    response => response,
    error => ResposeErrorHandle(error)
  )
  
  const request = <T = any>(url: string, config: AxiosRequestConfig, options?: UseAxiosOptions): UseAxiosReturn<T> =>{
    const token = getToken()
    if(token) {
      config = {
        ...config,
        headers:{
          Authorization: token
        }
      }
    }
    const result = useAxios<T>(url, config, instance, {...useAxiosOptions, ...options})
    watch([result.aborted],([aborted], _, onInvalidate) => {
      //  请求被取消
      if(aborted){
        console.log("请求被取消")
      }
    })
    return result
  }

  const get = <T = any>(params?: any, options?: UseAxiosOptions): UseAxiosReturn<Result<T>> => {
    if(params){
      params = {
        ...params,
        timer__: Date.now()
      }
    }
    return request(pathG, {method: 'GET', params}, options);
  }
  
  const post = <T = any>(data?: any, options?: UseAxiosOptions): UseAxiosReturn<Result<T>> => {
    return request(pathG, {data, method: 'POST'}, options);
  }

  return {
    get,
    post
  }
}

export default AppUseAxios 